# -*- coding=utf-8 -*-
import os
import data
import webapp2
import urllib2
from google.appengine.ext.webapp import template
from google.appengine.ext import ndb
from parsefeed import get_title
class AddSubscription(webapp2.RequestHandler):
    def post(self):
        data.Reader.get_or_insert('Reader')
        feedurl = self.request.get('feedurl')
        prompt = '添加成功！'
        try:
            feed = urllib2.urlopen(urllib2.Request(feedurl,
                                                   headers={'User-Agent':
                'Mozilla/5.0 (X11; Linux x86_64; rv:24.0) '
                'Gecko/20100101 Firefox/24.0'}))
        except:
            prompt = '订阅源下载失败，请检查地址是否正确！'
        else:
            try:
                title = get_title(feed)
            except:
                prompt = '订阅源XML解析失败，请检查地址是否正确！'
            else:
                newsub = data.Subscription(
                            key=ndb.Key('Subscription', feed.geturl()),
                            name=title)
                newsub.put()
        path = os.path.join(os.path.dirname(__file__), 'addsub.html')
        self.response.out.write(template.render(path, {'prompt': prompt}))

    def get(self):
        prompt = '添加订阅...'
        path = os.path.join(os.path.dirname(__file__), 'addsub.html')
        self.response.out.write(template.render(path, {'prompt': prompt}))


add = webapp2.WSGIApplication([('/addsub', AddSubscription)], debug=True)
